//
//  DLHistogramView.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/12/5.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLHistogramView.h"

@interface DLHistogramView()
@property (nonatomic, strong) ChartXAxis *xAxis;
@end

@implementation DLHistogramView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self layoutSubControls];
        
        self.xValuesDataSource = [NSMutableArray array];
        self.backgroundColor = kDLMachineTableAndCellBgColor;
        self.backgroundColor = [UIColor whiteColor];
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(17, 17)];
        
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = maskPath.bounds;
        maskLayer.path = maskPath.CGPath;
        self.layer.mask  = maskLayer;
    }
    return self;
}
//- (void) chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight {
//    NSLog(@"图表中的数值被选中");
//
//}
//- (void)chartTranslated:(ChartViewBase * _Nonnull)chartView dX:(CGFloat)dX dY:(CGFloat)dY {
//    NSLog(@"图表被移动");
//}
- (void)chartScaled:(ChartViewBase * _Nonnull)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY {
    
    ChartViewPortHandler *scalexxxxX = self.barChartView.viewPortHandler;
    NSLog(@"缩放了%.2f倍", scalexxxxX.scaleX);
}
- (void) setDataSourceDic:(NSDictionary *)dataSourceDic {
    _dataSourceDic = dataSourceDic;
//    NSLog(@"柱状图的数据源是：%@", dataSourceDic);
    NSDictionary *dic = dataSourceDic[@"data"];
    
    self.titleLabel.text = kFormatString(dic[@"pTitle"]);
    
    NSArray *setLabelArray = [NSArray arrayWithArray:dic[@"label"]];
    
    NSArray *kDataArray = [NSArray arrayWithArray:dic[@"kData"]];
    
    NSArray *kDataLabelArray = [NSArray arrayWithArray:dic[@"kData_label"]];
    
    if (setLabelArray.count > 1 && kDataArray.count > 1 && kDataLabelArray.count > 1) {
        //x轴
        for (NSInteger i = 0; i < kDataLabelArray.count; i++) {
            
            NSString *dateStr = kFormatString(kDataLabelArray[i]);
            [self.xValuesDataSource addObject:dateStr];
        }
        
        NSArray *colors = @[kColorRGB(146, 131, 227), kColorRGB(241, 143, 84), kColorRGB(234, 205, 166)];
        
        ChartIndexAxisValueFormatter *formatter = [[ChartIndexAxisValueFormatter alloc] initWithValues:self.xValuesDataSource];
        [self.barChartView.xAxis setValueFormatter:formatter];
        
        NSMutableArray *yValues = [NSMutableArray array];
        
        NSArray *kDataSubArr = kDataArray[0];//拿到柱状图柱的个数
        
        if (kDataSubArr.count > 0) {
            
            for (NSInteger i = 0; i < kDataSubArr.count; i++) {
                
                NSMutableArray *setArr = [NSMutableArray array];
                NSMutableArray *dataArr = [NSMutableArray array];
                
                for (NSInteger j = 0; j < kDataArray.count; j++) {
                    NSArray *arr = kDataArray[j];
                    NSString *dataStr = kFormatString(arr[i]);
                    [dataArr addObject:dataStr];
                }
                
                
                for (NSInteger j = 0; j < dataArr.count; j++) {
                    NSString *valueStr = [NSString stringWithFormat:@"%@", dataArr[j]];
                    BarChartDataEntry *yEntry = [[BarChartDataEntry alloc] initWithX:j y:valueStr.doubleValue];
                    [setArr addObject:yEntry];
                }
                
                BarChartDataSet *set = [[BarChartDataSet alloc] initWithValues:setArr label:kFormatString(setLabelArray[i])];
                
                NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
                //                    formatter.numberStyle = NSNumberFormatterDecimalStyle;
                [formatter setPositiveFormat:@"#0.00"];
                set.valueFormatter = [[ChartDefaultValueFormatter alloc] initWithFormatter: formatter];
                
                set.axisDependency = AxisDependencyLeft;
                
                UIColor *color = [colors objectAtIndex:i];
                [set setColor:color];
                set.valueColors = @[color];
                //在面板上直接显示数值
                set.drawValuesEnabled = YES;
                [yValues addObject:set];
            }
        }
        
        // 赋值数据
        BarChartData *data = [[BarChartData alloc] initWithDataSets:yValues];
        data.highlightEnabled = NO;
        
        
        self.barChartView.data = data;
        
        ChartViewPortHandler *scaleX = self.barChartView.viewPortHandler;
        
        //、、146 131 227- 241 143 84- 234 205 166
        //  161128基金持有人结构  399011基金持有人结构  161716基金持有人结构
        
        if (kDataSubArr.count == 1) {
            if (kDataLabelArray.count < 4) {
                data.barWidth = 0.2;
                [data groupBarsFromX:-0.5 groupSpace:0.4 barSpace:0];
                [scaleX setMinimumScaleX:1.05];
                [scaleX setMaximumScaleX:1.05];
            } else if (kDataLabelArray.count < 11) {
                data.barWidth = 0.3;
                [data groupBarsFromX:-0.5 groupSpace:0 barSpace:0];
                [scaleX setMinimumScaleX:1.0];
                [scaleX setMaximumScaleX:4.0];
            } else {
                //没有超过10个的目前 如果有就按照10个的比例来缩放
                data.barWidth = 0.3;
                [data groupBarsFromX:-0.5 groupSpace:0 barSpace:0];
                [scaleX setMinimumScaleX:1.0];
                [scaleX setMaximumScaleX:4.0];
            }
        } else if (kDataSubArr.count == 2) {
            data.barWidth = 0.3;
            [data groupBarsFromX:-0.5 groupSpace:0.4 barSpace:0];
            if (kDataLabelArray.count < 4) {
                [scaleX setMinimumScaleX:1.05];
                [scaleX setMaximumScaleX:1.05];
            } else if (kDataLabelArray.count < 11) {
                [scaleX setMinimumScaleX:2.25];
                [scaleX setMaximumScaleX:3.5];
            } else {
                //没有超过10个的目前 如果有就按照10个的比例来缩放
                [scaleX setMinimumScaleX:2.25];
                [scaleX setMaximumScaleX:3.5];
            }
        } else if (kDataSubArr.count == 3) {
            data.barWidth = 0.2;
            [data groupBarsFromX:-0.5 groupSpace:0.4 barSpace:0];
            if (kDataLabelArray.count < 4) {
                [scaleX setMinimumScaleX:1.2];
                [scaleX setMaximumScaleX:1.2];
            } else if (kDataLabelArray.count < 11) {
                [scaleX setMinimumScaleX:1.0];
                [scaleX setMaximumScaleX:4.2];
            } else {
                //没有超过10个的目前 如果有就按照10个的比例来缩放
                [scaleX setMinimumScaleX:1.0];
                [scaleX setMaximumScaleX:4.2];
            }
        } else {
            kShowRequestMsg(@"说好没有四个柱的~");
        }
    }
}
- (void) layoutSubControls {
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.frame = CGRectMake(12, 10, self.width - 24, 20);
    titleLabel.textColor = kDLNormalBlackColor;
    titleLabel.font = kBoldFont(14);
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.backgroundColor = [UIColor whiteColor];
    [self addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    BarChartView *barChartView = [[BarChartView alloc] initWithFrame:CGRectMake(kMachineChartsChartLeftMargin, 0, self.width - kMachineChartsChartLeftMargin *2, kMachineChartsHeight - 40)];
    [barChartView setExtraOffsetsWithLeft:0 top:50 right:0 bottom:0];
    [self addSubview:barChartView];
    barChartView.delegate = self;
    self.barChartView = barChartView;
    barChartView.backgroundColor = kDLMachineTableAndCellBgColor;
    barChartView.backgroundColor = kColorRandom;
    barChartView.backgroundColor = [UIColor whiteColor];
    
    barChartView.noDataText = @"暂无数据";//没有数据时的文字提示
    barChartView.drawValueAboveBarEnabled = YES;//数值显示在柱形的上面还是下面
    barChartView.drawBarShadowEnabled = NO;//是否绘制柱形的阴影背景
    
    barChartView.scaleYEnabled = NO;//取消Y轴缩放
    barChartView.scaleXEnabled = YES;//X轴缩放
    barChartView.doubleTapToZoomEnabled = NO;//取消双击缩放
    barChartView.dragEnabled = YES;//启用拖拽图表
    barChartView.dragDecelerationEnabled = YES;//拖拽后惯性效果
    barChartView.dragDecelerationFrictionCoef = 0.9;//拖拽后惯性效果的摩擦系数(0~1)，数值越小，惯性越不明显
    barChartView.legend.enabled = YES;//显示图例说明
    
    
    ChartXAxis *xAxis = barChartView.xAxis;
    self.xAxis = xAxis;
    xAxis.labelPosition = XAxisLabelPositionBottom;//X轴的显示位置，默认是显示在上面的
    xAxis.drawGridLinesEnabled = NO;//不绘制网格线
    xAxis.labelTextColor = kDLNormalBlackColor;//label文字颜色
    xAxis.axisLineWidth = 0.5;//设置X轴线宽
    xAxis.axisLineColor = [UIColor grayColor];
    xAxis.gridColor = [UIColor grayColor];
    xAxis.labelCount = 0;
    xAxis.forceLabelsEnabled = NO;
    
    ChartYAxis *leftAxis = barChartView.leftAxis;//获取左边Y轴
    leftAxis.drawGridLinesEnabled = YES;
    leftAxis.forceLabelsEnabled = NO;//不强制绘制制定数量的label
    leftAxis.axisLineWidth = 0.5;//Y轴线宽
    leftAxis.axisLineColor = [UIColor grayColor];//Y轴颜色
    leftAxis.labelPosition = YAxisLabelPositionOutsideChart;
    leftAxis.labelTextColor = kDLNormalBlackColor;
    leftAxis.labelFont = kSystemFont(12);
    
    
    leftAxis.inverted = NO;//是否将Y轴进行上下翻转
    leftAxis.axisMinimum = 0;
    
    leftAxis.gridLineDashLengths = @[@3.0f, @3.0f];//设置虚线样式的网格线
    leftAxis.gridColor = [UIColor grayColor];//网格线颜色
    leftAxis.gridAntialiasEnabled = YES;//开启抗锯齿
    leftAxis.drawGridLinesEnabled = NO;//不显示y轴数值对应的水平线
    
    
    barChartView.rightAxis.enabled = NO;
    
//    ChartLimitLine *limitLine = [[ChartLimitLine alloc] initWithLimit:80 label:@"限制线"];
//    limitLine.lineWidth = 5;
//    limitLine.lineColor = [UIColor greenColor];
//    limitLine.lineDashLengths = @[@5.0f, @5.0f];//虚线样式
//    limitLine.labelPosition = ChartLimitLabelPositionRightTop;//位置
//    [leftAxis addLimitLine:limitLine];//添加到Y轴上
    
    leftAxis.drawLimitLinesBehindDataEnabled = YES;//设置限制线绘制在柱形图的后面
    
    [self bringSubviewToFront:titleLabel];
    
    //设置y轴0.xx的时候显示0.xx而不是.xx
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setPositiveFormat:@"#0.00"];
    self.barChartView.leftAxis.valueFormatter = [[ChartDefaultAxisValueFormatter alloc] initWithFormatter:formatter];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
